import { Component, Director, director, Node, _decorator } from 'cc';
const { ccclass } = _decorator;

@ccclass('UIZOrder')

/**给子节点设置层级关系 */
export default class UIZOrder extends Component {
    private tempArr: Node[] = [];


    /**
     * 更新节点树排序
     */
    public updateZOrder() {

        //新增控制排序间隔，避免耗费太多性能
        if(!this.isUpdateZIndex) return;
        this.isUpdateZIndex = false;
        this.scheduleOnce(()=>{
            this.isUpdateZIndex = true;
        },0.1);
        
        Array.prototype.push.apply(this.tempArr, this.node.children);
        //根据y坐标调整节点排序
        this.tempArr.sort((a, b) => {
            // 首先判断a和b是否存在zIndex属性来决定排序依据

            let aIndex:number = a['zIndex'];
            let bIndex:number = b['zIndex'];
        
            if (aIndex && bIndex) {
                // 如果a和b都有zIndex属性，按照zIndex大小排序
                return a['zIndex'] - b['zIndex'];
            } else if (aIndex) {
                // 如果只有a有zIndex属性，那么a排在b前面
                return 1;
            } else if (bIndex) {
                // 如果只有b有zIndex属性，那么b排在a前面
                return -1;
            }
        
            // 如果a和b都没有zIndex属性，按照原来规则排序
            return (b.position.y - a.position.y) || (a.getSiblingIndex() - b.getSiblingIndex());
        })
        .forEach((child, index) => {
            child.setSiblingIndex(index);
        });

        this.tempArr.length = 0;
    }

    private isUpdateZIndex:boolean = true;
    protected update(dt: number): void {
        this.updateZOrder();
    }

}